package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/api/request"
	"shop/common/global"
	"shop/shop_grpc/proto/shop"
)

func CreateOrder(c *gin.Context) {
	var dev request.CreatOrderReq
	if err := c.ShouldBind(&dev); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	order, err := global.ShopClient.CreateSeckillOrder(c, &shop.CreateSeckillOrderRequest{
		UserId:         dev.UserId,
		SeckillGoodsId: dev.SeckillGoodsId,
		Num:            dev.Num,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": order,
	})
}

func Pay(c *gin.Context) {
	var dev request.PayOrderReq
	var status int64
	if err := c.ShouldBind(&dev); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
			"data": nil,
		})
		fmt.Print(err.Error(), 1)
		return
	}
	if dev.Status == "TRADE_SUCCESS" {
		status = 1
	}
	// 确保传递正确的订单号参数
	pay, err := global.ShopClient.OrderPay(c, &shop.OrderPayRequest{
		OrderNo: dev.Order, // 注意：这里dev.Order字段对应前端传递的out_trade_no
		Status:  status,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
			"data": nil,
		})
		fmt.Print(err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": pay,
	})
}
